<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title></title>
</head>
<body>

<input type="text" name="">
<button>查询</button>
<img src="">
<script type="text/javascript" src="./ajax.js"></script>
<script type="text/javascript">
	let btn = document.querySelector('button')
	let inp = document.querySelector('input')
	let img = document.querySelector('img')
	//用promise封装一下天气接口

	function weather(url) {
		return new Promise((resolve,reject)=>{
			let xhr = new XMLHttpRequest()

			xhr.open('get', url)
			xhr.send()
			xhr.onreadystatechange = function() {
			if(xhr.readyState == 4){
				let res = JSON.parse(xhr.responseText)
				if(res.code == 200){
					resolve(res)
				}else{
					reject(res)
			}
		}
	}
		})
	}
	
	btn.onclick = function() {
		weather(`https://geoapi.qweather.com/v2/city/lookup?location=${inp.value}&key=c494e264764449f7b4f6bf742276d7f9`).then((res)=>{
			console.log(res)
			let newUrl = `https://devapi.qweather.com/v7/weather/now?location=${res.location[0].id}&key=c494e264764449f7b4f6bf742276d7f9`
			return weather(newUrl)
		})
		.then((res)=>{
			img.src = `https://a.hecdn.net/img/common/icon/202106d/${res.now.icon}.png`
		})
		.catch((err)=>{
			console.log(err)
		})
	}
	ajax({
		method:'get',
		url:'https://geoapi.qweather.com/v2/city/lookup',
		params:{
			location:inp.value,
			key:c494e264764449f7b4f6bf742276d7f9

		}
	}).then(res=>{
		console.log(res,'==============')
	})

	
</script>
</body>
</html>